﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using com.ubosi.model.Entity;
using com.ubosi.dao;
using System.Data.SqlClient;
using com.ubosi.spider.config;
namespace com.ubosi.spider.app.Hotel
{
    public partial class frmHotelMap : Form
    {
        public frmHotelMap()
        {
            InitializeComponent();
            InitCityList();
        }

        private void btnAutoMap_Click(object sender, EventArgs e)
        {
            AutoMap();
            AutoMap1();
        }
        /// <summary>
        /// 自动映射
        /// </summary>
        private void AutoMap()
        {
            string sql = @"select tmp.*,ubosi.hotelid as ubosi_hotelid from hotel_temp tmp inner join
(select hotel.*,city.cityNameCn from hotel left join city on hotel.cityid=city.cityid) as ubosi
on tmp.cityname=ubosi.citynamecn and tmp.hotelname=ubosi.hotelname and tmp.ismap=0";
            UBOSIEntities entitys = new UBOSIEntities();
            int count = 0;
            SqlDataReader sqlDataReader = SqlHelper.ExecuteReader(SystemConfigManager.SystemConfig.ConnectionString, CommandType.Text, sql);
            while (sqlDataReader.Read())
            {
                
                try
                {
                    HotelMap hotelMap = HotelMap.CreateHotelMap((string)sqlDataReader["ubosi_hotelid"], (string)sqlDataReader["srcid"], (string)sqlDataReader["hotelid"]);
                    entitys.AddToHotelMap(hotelMap);
                    SqlHelper.ExecuteNonQuery(SystemConfigManager.SystemConfig.ConnectionString, CommandType.Text, string.Format("update hotel_temp set ismap=1 where hotelid='{0}'", sqlDataReader["hotelid"]));
                    entitys.SaveChanges();
                    count++;
                }
                catch
                {
                }
            }
            MessageBox.Show("自动映射了" + count.ToString() + "家酒店！");         
        }

        /// <summary>
        /// 自动模糊映射
        /// </summary>
        public void AutoMap1()
        {
            string sql = @"select * from hotel_temp where ismap=0";
            UBOSIEntities entitys = new UBOSIEntities();
            int count = 0;
            SqlDataReader sqlDataReader = SqlHelper.ExecuteReader(SystemConfigManager.SystemConfig.ConnectionString, CommandType.Text, sql);
            while (sqlDataReader.Read())
            {
                string conditioin = "";
                string hotelname = (string)sqlDataReader["hotelname"];
                hotelname = hotelname.Replace("大酒店", "").Replace("酒店", "").Replace("宾馆", "").Replace("大饭店", "").Replace("饭店", "").Replace("店","").Replace((string)sqlDataReader["cityname"],"").Replace("连锁","");
                
                if (string.IsNullOrEmpty(hotelname))
                    hotelname = (string)sqlDataReader["hotelname"];

                string[] arr = hotelname.Split('（');
                if (arr.Length == 1)
                    arr = hotelname.Split('(');
                foreach (string s in arr)
                {
                    string s1= s.Replace("(","").Replace("（","").Replace(")","").Replace("）","");
                    conditioin += string.IsNullOrEmpty(conditioin) ? string.Format("hotelname like '%{0}%'", s1) : string.Format("and hotelname like '%{0}%'", s1);
                }
                string sql1 = string.Format(@"select * from
  (select hotel.*,citynamecn from hotel left join city on city.cityid=hotel.cityid) as a
where
 citynamecn='{0}' and {1} and
 hotelid not in (select hotelid from hotelmap where srcid='17u')",sqlDataReader["cityname"],conditioin);                
                try
                {
                    DataSet ds = SqlHelper.ExecuteDataset(SystemConfigManager.SystemConfig.ConnectionString, CommandType.Text, sql1);
                    if (ds.Tables[0].Rows.Count != 1)
                        continue;

                    HotelMap hotelMap = HotelMap.CreateHotelMap((string)ds.Tables[0].Rows[0]["hotelid"], (string)sqlDataReader["srcid"], (string)sqlDataReader["hotelid"]);
                    entitys.AddToHotelMap(hotelMap);
                    SqlHelper.ExecuteNonQuery(SystemConfigManager.SystemConfig.ConnectionString, CommandType.Text, string.Format("update hotel_temp set ismap=1 where hotelid='{0}'", sqlDataReader["hotelid"]));
                    entitys.SaveChanges();
                    count++;
                }
                catch
                {
                }
            }
            MessageBox.Show("自动模糊映射了" + count.ToString() + "家酒店！"); 
        }
        /// <summary>
        /// 查找映射关系
        /// </summary>
        /// <param name="keyword"></param>
        private void FindMap(string keyword,string srcId,string cityname)
        {
            string sql =  string.Format(@"select citynamecn,hotelid,hotelname,hoteladdress from hotel left join city on hotel.cityid=city.cityid
where hotelid not in(select hotelid from hotelmap where srcid='{0}') and citynamecn='{1}' and hotelname like '%{2}%'", srcId, cityname,keyword);
            cblUbosi.Items.Clear();  
            SqlDataReader sqlDataReader = SqlHelper.ExecuteReader(SystemConfigManager.SystemConfig.ConnectionString, CommandType.Text, sql);
            while (sqlDataReader.Read())
            {
                KeyValuePair<string, string> kv = new KeyValuePair<string, string>((string)sqlDataReader["hotelid"], string.Format((string)sqlDataReader["hotelname"]+"--{0}", (string)sqlDataReader["hoteladdress"]));
                cblUbosi.Items.Add(kv);
            }            
            lblUbosi.Text = "游博士酒店=" + cblUbosi.Items.Count.ToString();
        }
        
        /// <summary>
        /// 查看没有映射的数据
        /// </summary>
        private void ViewNotMap(string srcId,string cityname)
        {
            string sqlUbosi = string.Format(@"select citynamecn,hotelid,hotelname,hoteladdress from hotel left join city on hotel.cityid=city.cityid
where hotelid not in(select hotelid from hotelmap where srcid='{0}') and citynamecn='{1}'", srcId, cityname);
            string sqlTmp = string.Format("select cityName,hotelid,hotelname from hotel_temp where isMap=0 and srcid='{0}' and cityname='{1}'", srcId, cityname);
            cblTemp.Items.Clear();
            cblUbosi.Items.Clear();            
            SqlDataReader sqlDataReader = SqlHelper.ExecuteReader(SystemConfigManager.SystemConfig.ConnectionString, CommandType.Text, sqlTmp);
            while (sqlDataReader.Read())
            {
                KeyValuePair<string, string> kv = new KeyValuePair<string, string>((string)sqlDataReader["hotelid"], (string)sqlDataReader["hotelname"]);
                cblTemp.Items.Add(kv);
            }
            sqlDataReader.Close();

            sqlDataReader = SqlHelper.ExecuteReader(SystemConfigManager.SystemConfig.ConnectionString, CommandType.Text, sqlUbosi);
            while (sqlDataReader.Read())
            {
                KeyValuePair<string, string> kv = new KeyValuePair<string, string>((string)sqlDataReader["hotelid"], string.Format((string)sqlDataReader["hotelname"] + "--{0}",sqlDataReader["hoteladdress"]));
                cblUbosi.Items.Add(kv);
            }

            sqlDataReader.Close();
            lblTemp.Text = "联盟网酒店=" + cblTemp.Items.Count.ToString();
            lblUbosi.Text = "游博士酒店=" + cblUbosi.Items.Count.ToString();
        }

        private void MaualMap(string hotelid, string srcHotelid, string srcId)
        {
            HotelMap hotelmap = HotelMap.CreateHotelMap(hotelid, srcId, srcHotelid);
            UBOSIEntities entitys = new UBOSIEntities();
            entitys.AddToHotelMap(hotelmap);
            SqlHelper.ExecuteNonQuery(SystemConfigManager.SystemConfig.ConnectionString, CommandType.Text, string.Format("update hotel_temp set ismap=1 where hotelid='{0}'", srcHotelid));
            entitys.SaveChanges();
            ViewNotMap(srcId, cbCityList.SelectedItem.ToString());
        }

        private void SetNoMap(string srcId,string hotelid)
        {
            SqlHelper.ExecuteNonQuery(SystemConfigManager.SystemConfig.ConnectionString, CommandType.Text, string.Format("update hotel_temp set ismap=2 where hotelid='{0}'", hotelid));
            ViewNotMap(srcId, cbCityList.SelectedItem.ToString());
        }

        private void InitCityList()
        {
            cbCityList.Items.Clear();
            UBOSIEntities entitys = new UBOSIEntities();
            var query = from city in entitys.City select city;
            foreach (var city in query)
            {
                cbCityList.Items.Add(city.CityNameCn);
            }
            cbCityList.SelectedIndex = 0;
        }
        
        private void btnViewMap_Click(object sender, EventArgs e)
        {
            ViewNotMap("17u",cbCityList.SelectedItem.ToString());
        }

        private void btnFindMap_Click(object sender, EventArgs e)
        {
            FindMap(txtKeyword.Text, "17u", cbCityList.SelectedItem.ToString());
        }

        private void cblTemp_ItemCheck(object sender, ItemCheckEventArgs e)
        {
            
        }

        private void cblTemp_SelectedIndexChanged(object sender, EventArgs e)
        {
            txtKeyword.Text = ((KeyValuePair<string, string>)cblTemp.Items[cblTemp.SelectedIndex]).Value;
            txtKeyword.Text = txtKeyword.Text.Replace(cbCityList.SelectedItem.ToString(), "").Replace("大酒店", "").Replace("酒店", "").Replace("宾馆", "").Replace("大饭店", "").Replace("饭店", "").Replace("连锁", "");
        }

        private void btnMap_Click(object sender, EventArgs e)
        {
            try
            {
                KeyValuePair<string, string> tmp = (KeyValuePair<string, string>)cblTemp.Items[cblTemp.SelectedIndex];
                KeyValuePair<string, string> ubosi = (KeyValuePair<string, string>)cblUbosi.Items[0];
                if (cblUbosi.Items.Count > 1)
                {
                    ubosi = (KeyValuePair<string, string>)cblUbosi.Items[cblUbosi.SelectedIndex];
                }


                MaualMap(ubosi.Key, tmp.Key, "17u");
            }
            catch(Exception ex)
            {
                MessageBox.Show("请选择" + ex.Message);
            }
        }

        private void btnNotMap_Click(object sender, EventArgs e)
        {
            if (cblTemp.SelectedIndex < 0)
            {
                MessageBox.Show("请选择联盟网站酒店");
                return;
            }
            KeyValuePair<string, string> tmp = (KeyValuePair<string, string>)cblTemp.Items[cblTemp.SelectedIndex];
            SetNoMap("17u", tmp.Key);
        }
    }
}
